package com.fy.utils.excel.listner;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fy.utils.excel.BaseExcel;
import com.fy.utils.excel.ExcelBaseUtil;
import com.fy.utils.excel.ExcelDataEnum;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户导入
 */
@Slf4j
public class ExcelDataListener extends AnalysisEventListener<BaseExcel> {

    Logger logger = LoggerFactory.getLogger(ExcelDataListener.class);


    /**
     * 300条处理一下
     */
    private static final int BATCH_COUNT = 300;
    List<BaseExcel> list = new ArrayList<>();
    private ExcelDataEnum excelDataEnum;
    private JSONObject param;
    private ExcelBaseUtil excelBaseUtil;


    /**
     *
     * @param excelDataEnum  导入数据类型
     * @param excelBaseUtil  工具类，添加新功能后需增加相应类型
     * @param param     跟随文件的其他业务参数
     */
    public ExcelDataListener(ExcelDataEnum excelDataEnum, ExcelBaseUtil excelBaseUtil, JSONObject param) {
        this.excelBaseUtil = excelBaseUtil;
        this.excelDataEnum = excelDataEnum;
        this.param = param;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        throw new RuntimeException(exception);
    }

    @Override
    public void invoke(BaseExcel data, AnalysisContext analysisContext) {
        logger.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("所有数据解析完成！");
        saveData();
    }

    private void saveData() {
        try {
            excelBaseUtil.saveData(excelDataEnum, list, param);
        }catch (Exception e){
           e.printStackTrace();

            throw e;
        }
    }

    public JSONObject getParam() {
        return param;
    }

    public void setParam(JSONObject param) {
        this.param = param;
    }
}
